const { default: toast } = require("../../miniprogram_npm/@vant/weapp/toast/toast");

// pages/symptoms/index.js
const app = getApp()
Page({
    data: {    
        buttonClasses: {}, // 用于存储每个按钮的类名
        activeNames: [],
        // 选中的文本索引
        chooseTxt: [],
        // 选中的文本内容
        chooseTxtContent: [],
        nextStepBtnActive: '',
        // 是否缓存了用户信息
        hasUserPhone: false,
        // 所有症状
        getSymptoms: [],
        // 当前输入的症状
        symptValue: '',
        showSearch: false,
        // 当前搜索症状匹配的数组
        searchVals: []
    },
    // 转至登陆授权页面
    toLogin() {
        wx.redirectTo({
            url: '/pages/login/index',
        })
    },
    onLoad() {
        // 未授权的先进行授权
        let isChooseProtocal = wx.getStorageSync('isChooseProtocal') ? wx.getStorageSync('isChooseProtocal') : false;

        // 授权
        if (!isChooseProtocal) {
            wx.setStorageSync('toMenu', '/pages/symptoms/index');
            this.toLogin();
        }
        let cacheUserInfo = wx.getStorageSync('user_phone');
        // 如果用户还未绑定登录
        if (cacheUserInfo.phoneNumber !== undefined && cacheUserInfo.phoneNumber.length > 0) {
            this.setData({
                hasUserPhone: true
            });
        }
    },
    onShow() {
        let that = this
        // 获取所有症状数据
        const initialButtonClasses = {};
        wx.request({
            url: app.globalData.domain + 'v4/symptom/getSymptoms',
            method: 'POST',
            success: function (res) {
            //   console.log('返回数据::', typeof(res.data.data), res.data.data);
                  
              if (res.data.code == 0) {
                // 循环列出有多少cell单元,暂时全部折叠起来
                var tempActiveNames = [];
                // res.data.data.forEach((ele, index) => {
                //     tempActiveNames.push(index + 1);
                //     ele.childs.forEach(item => {
                //         initialButtonClasses[item.id] = '';
                //     });
                // });
                that.setData({
                    getSymptoms: res.data.data,
                    activeNames: tempActiveNames,                    
                });
                const chooseTxtJsonStr = wx.getStorageSync('chooseTxt');
                const chooseTxtContentStr = wx.getStorageSync('chooseTxtContent');
                let chooseTxtJsonObj = [];
                let chooseTxtContentObj = [];

                if (chooseTxtJsonStr.length > 0) chooseTxtJsonObj = JSON.parse(chooseTxtJsonStr);
                if (chooseTxtContentStr.length > 0) chooseTxtContentObj = JSON.parse(chooseTxtContentStr);
                                            
                if (chooseTxtJsonObj !== undefined && chooseTxtJsonStr.length > 0) {
                    // 回显选中的症状
                    chooseTxtJsonObj.forEach(element => {
                        initialButtonClasses[element] = 'active';
                    });
                    // console.log('initialButtonClasses', initialButtonClasses, chooseTxtJsonObj);
                    that.setData({
                        buttonClasses: initialButtonClasses,
                        nextStepBtnActive: 'active',
                        chooseTxt: chooseTxtJsonObj,
                        chooseTxtContent: JSON.parse(chooseTxtContentStr),
                    });
                }
                console.log(that.data)  
              }
            }
        });             
    },
    onChange(event) {
        this.setData({
            activeNames: event.detail,
        });
    },
    toggleClass: function (event) {
        console.log('选中的文本', event.currentTarget.dataset.index, event.currentTarget.dataset.text);
        const index = event.currentTarget.dataset.index;
        const updatedButtonClasses = { ...this.data.buttonClasses };
        // console.log('updatedButtonClasses', updatedButtonClasses);
        // 最多5个症状
        // if (this.data.chooseTxt.length > 4) {
        //     wx.showToast({
        //       title: '症状的个数不超过5个',
        //       icon: 'none',             
        //       duration: 2000,           
        //       mask: true               
        //     });
        //     return ;
        // }
        if (this.data.chooseTxt.indexOf(index) < 0) {
            this.data.chooseTxt.push(index);
            updatedButtonClasses[index] = 'active';
            this.data.chooseTxtContent.push(event.currentTarget.dataset.text);
        } else {
            // 有元素,则移除
            this.data.chooseTxt = this.data.chooseTxt.filter(item => item !== index);
            this.data.chooseTxtContent = this.data.chooseTxtContent.filter(item => item !== event.currentTarget.dataset.text);
            updatedButtonClasses[index] = '';
        }
        // console.log('重新赋值后', this.data.buttonClasses);
        // 有选中的症状, 下一步按钮,就需要展示
        if (this.data.chooseTxt.length > 0) {
            this.setData({
                nextStepBtnActive: 'active'
            });
        } else {
            this.setData({
                nextStepBtnActive: ''
            });
        }
        // 选中的症状,存入缓存中
        wx.setStorageSync('chooseTxt', JSON.stringify(this.data.chooseTxt));
        wx.setStorageSync('chooseTxtContent', JSON.stringify(this.data.chooseTxtContent));

        this.setData({
            chooseTxt: this.data.chooseTxt,
            chooseTxtContent: this.data.chooseTxtContent,
            buttonClasses: updatedButtonClasses
        });
    },
    // 模糊匹配症状
    matchSymtoms(e) {
        const flag = e.detail.length > 0;
        let filtered = [];
        // 使用 flatMap 来扁平化结果
        if (flag) {
            filtered = this.data.getSymptoms.flatMap(item => {
                return item.childs
                    .filter(child => child.cur_name.includes(e.detail))
                    .map(child => ({ id: child.id, cur_name: child.cur_name })); // 返回所需格式
            });            
        }
    
        this.setData({
            showSearch: flag,
            searchVals: filtered
        });
    },
    // 点击确定症状
    confirmTxt(event) {
        const datasets = event.currentTarget.dataset;
        // 点击 确认,从搜索的下拉中移除
        const newSearchVals = [...this.data.searchVals]; 
        const filteredSymptoms = newSearchVals.filter(symptom => symptom.id !== datasets.index);
        // 清空输入框 + 隐藏 下拉搜索板块
        const newgetSymptoms = [...this.data.getSymptoms];
        const outerIds = [...this.data.activeNames];
        newgetSymptoms.forEach((item, index) => {
            item.childs.forEach(child => {
                if (child.id == datasets.index && !outerIds.includes(index+1)) {
                    outerIds.push(index+1);
                }
            });
        }); 
        console.log('outerIds::', outerIds);
        this.setData({
            symptValue: '',
            showSearch: false,
            searchVals: [],
            activeNames: outerIds
            // searchVals: filteredSymptoms
        });    
        // 执行选中逻辑
        this.toggleClass(event);            
    },
    nextStep() {
        // 未注册登录的, 进行注册登录
        let cacheUserInfo = wx.getStorageSync('user_phone');
        // 未注册的用户,先注册
        if (cacheUserInfo.length == 0) {

        } else {
            wx.navigateTo({
                url: '/pages/symptoms/second',
            })
        }
    },
    getPhoneNumber(e) {
        console.log(e);
        let {
            encryptedData,
            iv,
            code
        } = e.detail
        // 如果授权获取手机号则进入下个页面 
        if (code) {
            this.getPhone(code)
        } else {
            Dialog.alert({
                title: '温馨提示',
                message: '请授权登录',
                theme: 'round-button',
            }).then(() => {
                // on close
            });
        }
    },
    // 用户获取手机号
    getPhone(code) {
        let that = this
        var reqUri = app.globalData.domain + 'index/index/getUserWxPhone';
        wx.request({
            url: reqUri,
            method: 'POST',
            data: {
                code,
            },
            success(res) {
                console.log(res)
                if (res.data.code == app.globalData.successCode) {
                    let {
                        phoneNumber
                    } = res.data.data
                    // 将用户的 手机号缓存
                    wx.setStorageSync('user_phone', res.data.data)
                    that.login(phoneNumber)
                } else {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg
                    })
                    return;
                }
            }
        })
    },
    // 用户登录
    login(phone) {
        let that = this
        var reqUri = app.globalData.domain + 'index/index/doReg';
        var uid = wx.getStorageSync('toid') ?? 0;
        let cid3 = wx.getStorageSync('tocid3');

        if (!cid3 || cid3 == undefined) cid3 = that.data.cid3;
        wx.request({
            url: reqUri,
            method: 'POST',
            data: {
                phone,
                types: 'mini',
                openid: app.globalData.openId,
                uid: uid,
                cid3: cid3,
                agentId: wx.getStorageSync('agentId') ?? 1
            },
            success(res) {
                console.log(res)
                if (res.data.code == app.globalData.successCode) {
                    wx.setStorageSync('isLogin', true);
                    that.setData({
                        hasUserPhone: true
                    });
                } else {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg
                    })
                    return;
                }
            }
        })
    },
    onShareAppMessage() {
        let that = this;
        return {
            title: '天纪云',
            path: '/pages/symptoms/index'
        }
    },
    onShareTimeline() {
        let that = this;
        return {
            title: '天纪云',
            path: '/pages/symptoms/index'
        }
    },    
})